<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 16/7/28
 * Time: 下午2:17
 */
class ReportTask extends Eloquent
{
    public static function task($type,$begin_date,$end_date,$shop_id,$data_id = null){
        //如果查询时间在一周内,切特殊报表,不进入计划任务队列
       if( ((strtotime($end_date) - strtotime($begin_date)) <= (60 * 60 * 24 * 7)) || in_array($type,array('temp_get_order_detail','temp_get_work_hour_report','temp_get_export_detail')) ){
        // if( in_array($type,array('temp_get_order_detail','temp_get_work_hour_report','temp_get_export_detail')) ){
            $return = array(
                'status' => 3,
                'data' => ReportTask::get_report_data($type,$begin_date,$end_date,$shop_id,$data_id)
            );
        }else{
            $index = md5($type.$shop_id.$begin_date.$end_date.$data_id);
            $report_task_record = ReportTaskRecords::where('index',$index)->first();
            if(!is_null($report_task_record)){
                $status = $report_task_record->status;
                if(in_array($status,array(1,2))){
                    $return = array(
                        'status' => $status,
                        'data' => ''
                    );
                }elseif($status == 0){
                    $return = ReportTask::add($index,$type,$begin_date,$end_date,$shop_id,$data_id);
                }elseif($status == 3){
                    if(time() > strtotime($report_task_record->task_expired_at)){
                        $return = ReportTask::add($index,$type,$begin_date,$end_date,$shop_id,$data_id);
                    }else{
                        $return = array(
                            'status' => $status,
                            'data' => unserialize(gzuncompress(base64_decode($report_task_record->data)))
                        );
                    }
                }
            }else{
                $return = ReportTask::add($index,$type,$begin_date,$end_date,$shop_id,$data_id);
            }
        }
        return $return;
    }

    /*
     * 获取报表数据
     * */
    public static function get_report_data($type,$begin_date,$end_date,$shop_id,$data_id){
        switch ($type){
            case 'get_profit_report': //订单类-毛利率分析
                $data = Report::get_profit_report($begin_date,$end_date,$shop_id);
                break;
            case 'get_check_inventory_supply': //库存类-盘点明细
                $data = Report::get_check_inventory_supply($begin_date,$end_date,$shop_id);
                break;
            case 'get_storage_detail': //库存类-入库明细
                $data = Report::get_storage_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_out_detail': //库存类-出库明细
                $data = Report::get_out_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_supply_stock_new': //库存类-结算进销存耗材明细 and 库存类-结算进销存分类统计
                $data = Report::get_supply_stock_new($begin_date,$end_date,$data_id,$shop_id);
                break;
            case 'get_supply_stock': //库存类-进销存耗材明细 and 库存类-进销存分类统计
                $data = Report::get_supply_stock($begin_date,$end_date,$data_id,$shop_id);
                break;
            case 'get_engineer_work_detail': //员工绩效-技师工作绩效明细 and 员工绩效-技师工作绩效统计
                $data = Report::get_engineer_work_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_company_credit_detail': //经营情况-应收账款明细
                $data = Report::get_company_credit_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_company_credit_sum': //经营情况-应收账款统计
                $data = Report::get_company_credit_sum($begin_date,$end_date,$shop_id);
                break;
            case 'get_export_detail': //经营情况-油品营业分析 and 经营情况-耗材营业分析 and 订单类-订单维修耗材出库明细
                $data = Report::get_export_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_work_hour_product': //经营情况-服务营业分析
                $data = Report::get_work_hour_product($begin_date,$end_date,$shop_id);
                break;
            case 'get_order_income': //订单类-订单明细
                $data = Report::get_order_income($begin_date,$end_date,$shop_id);
                break;
            case 'get_order_derate_detail': //订单类-订单减免明细
                $data = Report::get_order_derate_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_order_parts': //订单类-订单耗材明细 and 订单类-订单耗材分类统计
                $data = Report::get_order_parts($begin_date,$end_date,$shop_id);
                break;
            case 'get_work_hour_report': //订单类-订单工时明细 and 订单类-订单服务分类统计
                $data = Report::get_work_hour_report($begin_date,$end_date,$shop_id);
                break;
            case 'temp_get_order_detail': //订单类-未结算订单明细
                $data = Report::temp_get_order_detail($shop_id);
                break;
            case 'temp_get_work_hour_report': //订单类-未结算订单工时分类明细
                $data = Report::temp_get_work_hour_report($shop_id);
                break;
            case 'temp_get_export_detail': //订单类-未结算订单维修产品出库明细
                $data = Report::temp_get_export_detail($shop_id);
                break;
            case 'get_return_order_detail': //退货的详情 
                $data = Report::get_return_order_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_engineer_supply_detail': //技师耗材业绩明细 
                $data = Report::get_engineer_supply_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_enterprice_order_detail': //技师耗材业绩明细 
                $data = Report::get_enterprice_order_detail($begin_date,$end_date,$shop_id);
                break;
            case 'get_bpjx_detail': //钣金喷漆业绩报表 
                $data = ReportService::get_bpjx_detail($begin_date,$end_date,$shop_id);
                break;
            default :
                $data = '';
                break;
        }
        return $data;
    }


    /*
     * 任务执行
     * */
    public static function exec(){
        $report_task_record = ReportTaskRecords::where('status',1)->first();
        if(!is_null($report_task_record)){
            $type = $report_task_record->report_type;
            $report_argv = explode('&',$report_task_record->report_argv);
            $shop_id = $report_argv['0'];
            $begin_date = $report_argv['1'];
            $end_date = $report_argv['2'];
            $data_id = $report_argv['3'];

            $report_task_record->status = 2;
            $report_task_record->save();


            try{
                $data = ReportTask::get_report_data($type,$begin_date,$end_date,$shop_id,$data_id);

                $data = base64_encode(gzcompress(serialize($data),9));
                $report_task_record->status = 3;
                $report_task_record->data = $data;
                $report_task_record->save();
            } catch (Exception $e) {
                $report_task_record->status = 4;
                $report_task_record->data = $e;
                $report_task_record->save();
            }
        }
    }

    /*
     * 获取过期时间
     * */
    public static function get_expired_date($type){
        switch ($type) {
            case 'year':
                $time = Common::num2DateTime(time() + 60 * 60 * 24 * 365);
                break;
            case "month":
                $time = Common::num2DateTime(time() + 60 * 60 * 24 * 31);
                break;
            case "week":
                $time = Common::num2DateTime(time() + 60 * 60 * 24 * 7);
                break;
            case "day":
                $time = Common::num2DateTime(time() + 60 * 60 * 24);
                break;
            default :
                $time = Common::num2DateTime(time() + 60 * 10);
                break;
        }
        return $time;
    }


    /*
     * 增加任务
     * */
    public static function add($index,$type,$begin_date,$end_date,$shop_id,$data_id){
        try{
            $report_task_record = ReportTaskRecords::where('index',$index)->first();
            if(is_null($report_task_record)) $report_task_record = new ReportTaskRecords();
            $report_task_record->index = $index;
            $report_task_record->report_type = $type;
            $report_task_record->report_argv = $shop_id.'&'.$begin_date.'&'.$end_date.'&'.$data_id;
            $report_task_record->status = 1;
            $report_task_record->task_expired_at = ReportTask::get_expired_date($type);
            $report_task_record->save();

            $return = array(
                'status' => 1,
                'data' => ''
            );
        } catch (Exception $e) {
            $return = array(
                'status' => 0,
                'data' => $e
            );
        }
        return $return;
    }

    /*
     * 流水表加工
     * */
    public static function operating_rule($shop_id,$date){
        try{
            $order_services = null;
            $order_parts = null;
            $order_profits = null;
            $operating_rules = ReportOperatingRule::where('status',1)
//                ->where('id',36)
                ->orderBy('classes_1_sort', 'asc')
                ->orderBy('classes_2_sort', 'asc')
                ->get();
            foreach ($operating_rules as $_operating_rule){
                $break_for=0;
                if(strlen($_operating_rule->item_rule) == 0){
                    $value = 0;
                }else{
                    $rule = explode(':',$_operating_rule->item_rule);
                    switch ($rule[0]){
                        case 'sql':
                            $sql = str_replace('#shop_id#',$shop_id,$rule[1]);
                            $sql = str_replace('#date#',$date,$sql);    
                            $result = DB::select($sql);
                            $value = $result[0]->value?$result[0]->value:0;
                            break;
                        case 'function':
                            if($rule[1] == 'jindiancheliang'){
                                $break_for=1;
                                $value=ReportDateReocrd::getShopCarDate($date,$shop_id);
                            }
                            if($rule[1] == 'old_custome'){
                                $value=ReportDateReocrd::getOldCustome($date,$shop_id);
                            }
                            
                            break;
                        case 'array':
                            $value = 0;
                            if($rule[1] == 'order_services'){
                                if(is_null($order_services)){
                                    $order_services = Report::get_order_services($date.' 00:00:00',$date.' 23:59:59',$shop_id);
                                } 
                                foreach ($order_services as $_order_services){                                    
                                    if(in_array($_order_services['level_3_id'],explode(",",$rule[2]))){
                                        $value = $value + 1;                                        
                                    }
                                }
                            }
                            if($rule[1] == 'order_parts'){
                                if(is_null($order_parts)){
                                    $order_parts = Report::get_export_detail($date.' 00:00:00',$date.' 23:59:59',$shop_id);
                                }
                                foreach ($order_parts as $_order_parts){
                                    if(in_array($_order_parts['level_3_id'],explode(",",$rule[2]))){
                                        if($_order_parts['return_type']==0){
                                            $value = $value + (int)$_order_parts['number'];
                                        }else{
                                            $value = $value + (int)$_order_parts['number'];//后来数量变为负数此地 直接相加 
                                        }
                                        
                                    }
                                }
                            }
                            if($rule[1] == 'order_profit'){
                                if(is_null($order_profits)){
                                    $order_profits = Report::get_profit_report($date.' 00:00:00',$date.' 23:59:59',$shop_id);
                                }
                                foreach ($order_profits as $_order_profit){
                                    if(isset($_order_profit[$rule[2]])){
                                        $value = $value + (int)$_order_profit[$rule[2]];
                                    }
                                }
                            }
                            break;
                        default :
                            $value = 0;
                            break;
                    }
                }
                if($break_for==1){
                    foreach ($value as $_v) {
                        $operating_data = ReportOperatingData::where('date',$date)
                            ->where('shop',$shop_id)
                            ->where('classes_1',$_v["classes_1"])
                            ->where('classes_2',$_v["classes_2"])
                            ->where('key',$_v["key"])
                            ->first();
                        if(is_null($operating_data)) $operating_data = new ReportOperatingData();
                        $operating_data->date = $date;
                        $operating_data->shop = $shop_id;
                        $operating_data->classes_1 = $_v["classes_1"];
                        $operating_data->classes_2 = $_v["classes_2"];
                        $operating_data->zh = $_v["zh"];
                        $operating_data->key = $_v["key"];
                        $operating_data->value = $_v["value"];
                        $operating_data->save();
                    }                    
                }else{
                     $operating_data = ReportOperatingData::where('date',$date)
                        ->where('shop',$shop_id)
                        ->where('classes_1',$_operating_rule->classes_1)
                        ->where('classes_2',$_operating_rule->classes_2)
                        ->where('key',$_operating_rule->item_en_name)
                        ->first();
                    if(is_null($operating_data)) $operating_data = new ReportOperatingData();
                    $operating_data->date = $date;
                    $operating_data->shop = $shop_id;
                    $operating_data->classes_1 = $_operating_rule->classes_1;
                    $operating_data->classes_2 = $_operating_rule->classes_2;
                    $operating_data->zh = $_operating_rule->item_zh_name;
                    $operating_data->key = $_operating_rule->item_en_name;
                    $operating_data->value = $value;
                    $operating_data->save();
                }
            }
        } catch (Exception $e) {
            Log::info($e);
            return -1;
        }
        return 0;
    }
}